package com.java.simple.study.juc.p3.deadlock.v2;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhoujl
 * @date 2022/5/10 21:04
 * @desc
 */
public class TestDeadLock {

    public static void main(String[] args) {
        Chopstick c1 = new Chopstick("c1");
        Chopstick c2 = new Chopstick("c2");
        Chopstick c3 = new Chopstick("c3");
        Chopstick c4 = new Chopstick("c4");
        Chopstick c5 = new Chopstick("c5");

        new Philosopher("苏格拉底", c1, c2).start();
        new Philosopher("柏拉图", c2, c3).start();
        new Philosopher("亚里斯多德", c3, c4).start();
        new Philosopher("赫拉克利克", c4, c5).start();
        new Philosopher("阿基米德", c5, c1).start();
    }

}

@Slf4j(topic = "c.Philosopher")
class Philosopher extends Thread {
    private final Chopstick left;
    private final Chopstick right;

    public Philosopher(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    private void eat() {
        log.debug("eating...");
        Sleeper.sleep(1);
    }

    @Override
    public void run() {
        while (true) {
            // 获得左手筷子
            if (left.tryLock()) {
                try {
                    // 获得右手筷子
                    if (right.tryLock()) {
                        try {
                            eat();
                        } finally {
                            // 释放右手筷子
                            right.unlock();
                        }
                    }
                } finally {
                    // 释放左手筷子
                    left.unlock();
                }
            }
        }
    }
}

class Chopstick extends ReentrantLock {
    private final String name;

    public Chopstick(String name) {
        // 是否公平锁-->解决饥饿问题  耗性能  不建议使用
        //super(true);
        this.name = name;
    }

    @Override
    public String toString() {
        return "Chopstick{" +
                "name='" + name + '\'' +
                '}';
    }
}
